<template>
  <!-- 顶部导航栏的通知铃铛组件 -->
  <el-popover
    placement="bottom"
    :width="400"
    trigger="click"
    @show="handlePopoverShow"
  >
    <template #reference>
      <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
        <el-icon :size="20" class="notification-bell">
          <Bell />
        </el-icon>
      </el-badge>
    </template>

    <!-- 弹出框内容 -->
    <div class="notification-popover">
      <!-- 头部 -->
      <div class="popover-header">
        <span class="title">通知</span>
        <el-button type="text" size="small" @click="handleMarkAllAsRead">
          全部已读
        </el-button>
      </div>

      <!-- 通知列表 -->
      <div v-loading="loading" class="notification-list">
        <div
          v-for="notification in latestNotifications"
          :key="notification.id"
          class="notification-item"
          :class="{ unread: !notification.isRead }"
          @click="handleNotificationClick(notification)"
        >
          <el-avatar :src="notification.sender?.avatar" size="small">
            {{ notification.sender?.nickName?.charAt(0) }}
          </el-avatar>
          <div class="notification-content">
            <div class="notification-text">
              <span class="sender-name">{{
                notification.sender?.nickName
              }}</span>
              <span class="action-text">{{ notification.actionText }}</span>
            </div>
            <div v-if="notification.target" class="notification-target">
              {{ notification.target.title }}
            </div>
            <div class="notification-time">
              {{ formatTime(notification.createTime) }}
            </div>
          </div>
          <div v-if="!notification.isRead" class="unread-dot" />
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && latestNotifications.length === 0"
          description="暂无通知"
          :image-size="80"
        />
      </div>

      <!-- 底部 -->
      <div class="popover-footer">
        <el-button type="text" @click="goToNotificationCenter">
          查看全部通知
        </el-button>
      </div>
    </div>
  </el-popover>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Bell } from "@element-plus/icons-vue";
import {
  getLatestNotifications,
  getNotificationStats,
  markAllAsRead,
  markAsRead
} from "@/api/notification";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";

const router = useRouter();
const loading = ref(false);
const latestNotifications = ref([]);
const unreadCount = ref(0);

// 加载最新通知
const loadLatestNotifications = async () => {
  loading.value = true;
  try {
    const response = await getLatestNotifications(10);
    if (response.code === 200) {
      latestNotifications.value = response.data;
    }
  } catch (error) {
    console.error("加载通知失败", error);
  } finally {
    loading.value = false;
  }
};

// 加载未读数量
const loadUnreadCount = async () => {
  try {
    const response = await getNotificationStats();
    if (response.code === 200) {
      unreadCount.value = response.data.totalUnreadCount || 0;
    }
  } catch (error) {
    console.error("加载未读数量失败", error);
  }
};

// 弹出框显示时刷新数据
const handlePopoverShow = () => {
  loadLatestNotifications();
  loadUnreadCount();
};

// 点击通知项
const handleNotificationClick = async notification => {
  // 标记为已读
  if (!notification.isRead) {
    try {
      await markAsRead(notification.id);
      notification.isRead = true;
      unreadCount.value = Math.max(0, unreadCount.value - 1);
    } catch (error) {
      console.error("标记已读失败", error);
    }
  }

  // 跳转到目标页面
  if (notification.target?.url) {
    router.push(notification.target.url);
  }
};

// 全部标记为已读
const handleMarkAllAsRead = async () => {
  try {
    const response = await markAllAsRead();
    if (response.code === 200) {
      ElMessage.success("已全部标记为已读");
      latestNotifications.value.forEach(n => (n.isRead = true));
      unreadCount.value = 0;
    }
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};

// 跳转到通知中心
const goToNotificationCenter = () => {
  router.push("/notifications");
};

// 格式化时间
const formatTime = time => {
  if (!time) return "";
  return formatDistanceToNow(new Date(time), {
    addSuffix: true,
    locale: zhCN
  });
};

// 初始化
onMounted(() => {
  loadUnreadCount();

  // 定时刷新未读数量（每30秒）
  setInterval(() => {
    loadUnreadCount();
  }, 30000);
});

// 暴露刷新方法供外部调用
defineExpose({
  refresh: () => {
    loadLatestNotifications();
    loadUnreadCount();
  }
});
</script>

<style scoped lang="scss">
.notification-bell {
  color: #606266;
  cursor: pointer;
  transition: color 0.3s;

  &:hover {
    color: #409eff;
  }
}

.notification-popover {
  .popover-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 12px;
    border-bottom: 1px solid #e8e8e8;

    .title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .notification-list {
    max-height: 400px;
    margin: 12px 0;
    overflow-y: auto;
  }

  .notification-item {
    position: relative;
    display: flex;
    align-items: flex-start;
    padding: 12px;
    cursor: pointer;
    border-radius: 4px;
    transition: background 0.3s;

    &:hover {
      background: #f5f7fa;
    }

    &.unread {
      background: #f0f9ff;
    }

    .el-avatar {
      flex-shrink: 0;
      margin-right: 12px;
    }

    .notification-content {
      flex: 1;
      min-width: 0;

      .notification-text {
        margin-bottom: 4px;

        .sender-name {
          margin-right: 4px;
          font-weight: 500;
          color: #303133;
        }

        .action-text {
          font-size: 14px;
          color: #606266;
        }
      }

      .notification-target {
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 13px;
        color: #409eff;
        white-space: nowrap;
      }

      .notification-time {
        font-size: 12px;
        color: #c0c4cc;
      }
    }

    .unread-dot {
      position: absolute;
      top: 16px;
      right: 12px;
      width: 8px;
      height: 8px;
      background: #409eff;
      border-radius: 50%;
    }
  }

  .popover-footer {
    padding-top: 12px;
    text-align: center;
    border-top: 1px solid #e8e8e8;
  }
}
</style>
